package main

import (
	"bufio"
	"fmt"
	"net"
	"strings"
	"sync"
	"time"
)

func main() {
	server, err := net.Listen("tcp", "127.0.0.1:8080")
	if err != nil {
		fmt.Println()
		return
	}
	//
	for {
		conn, err := server.Accept()
		if err != nil {
			fmt.Println()
			continue
		}
		go handleConn(conn)
	}

}

func echo(c net.Conn, shout string, delay time.Duration) {
	fmt.Fprintln(c, "\t", strings.ToUpper(shout))
	time.Sleep(delay)
	fmt.Fprintln(c, "\t", shout)
	time.Sleep(delay)
	fmt.Fprintln(c, "\t", strings.ToLower(shout))
}

func handleConn(c net.Conn) {
	var wg sync.WaitGroup
	input := bufio.NewScanner(c)
	for input.Scan() {
		wg.Add(1)
		go func(line string) {
			defer wg.Done()
			go echo(c, line, 1*time.Second)
		}(input.Text())
	}

	wg.Wait()
	if tc, err := c.(*net.TCPConn); err {
		tc.CloseWrite()
	}
	c.Close()

}
